<template>
  <div class="losses-page">
    <!-- 数据筛选 -->
    <el-card class="filter-card" shadow="never">
      <div class="filter-title">数据筛选</div>
      <el-form :inline="true" :model="filter" class="filter-form">
        <el-form-item label="报损单号：">
          <el-input v-model="filter.ReportlossId" placeholder="请输入/扫描单号" clearable style="width: 180px;" />
        </el-form-item>
        <el-form-item label="单据类型：">
          <el-select v-model="filter.ReportlossType" placeholder="请选择" style="width: 120px;">
            <el-option v-for="opt in typeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="单据状态：">
          <el-select v-model="filter.State" placeholder="请选择" style="width: 120px;">
            <el-option v-for="opt in statusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="ShowReportlosses"><el-icon>
              <Search />
            </el-icon>查询</el-button>
          <el-button @click="handleReset"><el-icon>
              <Refresh />
            </el-icon>重置</el-button>
        </el-form-item>
        <div style="flex:1;text-align:right;">
          <el-link type="primary">高级搜索</el-link>
        </div>
      </el-form>
    </el-card>

    <!-- 数据列表操作栏 -->
    <el-card class="table-card" shadow="never">
      <div class="table-toolbar">
        <span class="table-title">数据列表</span>
        <div class="table-actions">
          <el-button type="primary" size="small" icon="Plus" @click="openDialog">新增</el-button>
          <el-button size="small" icon="Edit">编辑</el-button>
          <el-button size="small" icon="Delete">删除</el-button>
          <el-button size="small" icon="Download">导出</el-button>
        </div>
      </div>
      <!-- 数据表格 -->
      <el-table :data="tableData" border style="width: 100%; margin-top: 10px;">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="reportlossId" label="报损单号" width="100" />
        <el-table-column prop="productName" label="产品名称" width="160" />
        <el-table-column prop="productCode" label="产品编码" width="120" />
        <el-table-column prop="specifications" label="规格" width="60" />
        <el-table-column prop="quantity" label="数量" width="60" />
        <el-table-column prop="depotName" label="仓库" width="80" />
        <el-table-column prop="locationName" label="原库位" width="120" />
        <el-table-column prop="lossLocation" label="报损库位" width="120" />
        <el-table-column prop="reportlossType" label="报损类型" width="100">
          <template #default="scope">
            <span v-if="scope.row.reportlossType == 1">损坏报损</span>
            <span v-if="scope.row.reportlossType == 2">丢失报损</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="90">
          <template #default="scope">
            <span v-if="scope.row.state == 0">等待审核</span>
            <span v-if="scope.row.state == 1">审核成功</span>
            <span v-if="scope.row.state == 2">审核失败</span>
          </template>
        </el-table-column>
        <el-table-column prop="auditor" label="审核人" width="80" />
        <el-table-column prop="auditTime" label="审核时间" width="120" />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-link type="primary" :underline="false">查看</el-link>
            <el-link type="primary" :underline="false" style="margin-left: 8px;"
              @click="editDialog(scope.row)">编辑</el-link>
            <el-link type="primary" :underline="false" style="margin-left: 8px;">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
      <!-- 批量操作栏和分页 -->
      <div class="table-footer">
        <div class="batch-actions">
          <el-button size="small">全选</el-button>
          <el-button size="small">反选</el-button>
          <el-select size="small" placeholder="批量操作" style="width: 120px;">
            <el-option label="批量删除" value="delete" />
            <el-option label="批量导出" value="export" />
          </el-select>
        </div>
        <div class="demo-pagination-block">
          <el-pagination v-model:current-page="Total.PageIndex" v-model:page-size="Total.PageSize"
            :page-sizes="[15, 30, 45, 60]" :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="Total.totalCount" />
        </div>
      </div>
    </el-card>
  </div>

  <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑报损单' : '新增报损单'" width="80%">
    <el-form :model="lossForm" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="报损单号">
            <el-input v-model="lossForm.reportlossId" placeholder="可不填写，自动生成" :disabled="isEdit" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="报损类型" required>
            <el-select v-model="lossForm.reportlossType" placeholder="请选择报损类型">
              <el-option label="损坏报损" value="损坏报损" />
              <el-option label="丢失报损" value="丢失报损" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="关联订单号">
            <el-input v-model="lossForm.orderNumber" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="制单人">
            <el-input v-model="lossForm.orderCreator" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="制单时间">
            <el-date-picker v-model="lossForm.orderCreatorTime" type="date" placeholder="请选择日期" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注">
        <el-input v-model="lossForm.note" type="textarea" :rows="3" maxlength="300" show-word-limit
          placeholder="请输入备注信息" />
      </el-form-item>
    </el-form>
    <div style="margin: 20px 0 10px 0; font-weight: bold;">产品信息</div>
    <el-button type="primary" size="small" @click="fetchProducts" style="margin-bottom: 10px;">新增产品</el-button>
    <el-table :data="lossesproducts" border>
      <el-table-column type="selection" width="50" />
      <el-table-column prop="productName" label="产品名称" width="120" />
      <el-table-column prop="productCode" label="产品编码" width="100" />
      <el-table-column prop="specifications" label="规格" width="80" />
      <el-table-column prop="price" label="单价" width="80" />
      <el-table-column prop="quantity" label="报损数量" width="100">
        <template #default="scope">
          <el-input v-model.number="scope.row.quantity" type="number" min="1" style="width: 100%;" />
        </template>
      </el-table-column>
      <el-table-column prop="locationName" label="当前库位" width="120" />
      <el-table-column label="操作" width="80">
        <template #default="scope">
          <el-link type="danger" @click="lossForm.products.splice(scope.$index, 1)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align: right; margin-top: 10px;">
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="">{{ isEdit ? '更新' : '提交' }}</el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import http from '@/http/axiosHelper'
import axios from 'axios'
import { ElMessage } from 'element-plus'
onMounted(() => {
  ShowReportlosses()
})
const filter = ref({
  ReportlossId: '',
  ReportlossType: '',
  State: ''
})
const typeOptions = [
  { label: '请选择', value: '' },
  { label: '类型A', value: 'A' },
  { label: '类型B', value: 'B' }
]
const statusOptions = [
  { label: '请选择', value: '' },
  { label: '等待审核', value: '0' },
  { label: '审核成功', value: '1' },
  { label: '审核失败', value: '2' }
]
const Total = ref({
  PageSize: 15,
  PageIndex: 1,
  totalPage: 1,
  totalCount: 1
})
const tableData = ref([])
const ShowReportlosses = () => {
  http.get("/lssueread/api/Reportloss/GetReportloss", {
    params: {
      PageSize: Total.value.PageSize,
      PageIndex: Total.value.PageIndex,
      ReportlossId: filter.value.ReportlossId,
      ReportlossType: filter.value.ReportlossType,
      State: filter.value.State
    }
  }).then(res => {
    tableData.value = res.data.pageDatas
    Total.value.totalCount = res.data.totalCount
    Total.value.totalPage = res.data.totalPage
  })
}

const handleReset = () => {
  filter.value = { ReportlossId: '', ReportlossType: '', State: '' }
}

const dialogVisible = ref(false)
const isEdit = ref(false)

const lossForm = reactive({
  "reportlossId": "",
  "orderNumber": "",
  "reportlossType": "",
  "note": "",
  "orderCreator": "",
  "orderCreatorTime": "",
  "state": 0,
  "reviewer": 0,
  "reviewerTime": "",
  "products": [
    {
      "reportlossId": "",
      "productId": "",
      "quantity": "",
      "createTime": ""
    }
  ]
})

const openDialog = () => {
 const now = new Date();
  const pad = (n: number) => n.toString().padStart(2, '0');
  const reportlossId = 
    pad(now.getHours()) + 
    pad(now.getMinutes()) + 
    pad(now.getSeconds());
  isEdit.value = false
  // 重置表单数据
  Object.assign(lossForm, {
    reportlossId: reportlossId,
    reportlossType: '',
    orderNumber: '',
    orderCreator: '',
    orderCreatorTime: '',
    note: '',
    products: [] as any[]
  })
  dialogVisible.value = true
}

// 编辑弹窗方法
const editDialog = (row: any) => {
  isEdit.value = true
  // 回填基本信息
  Object.assign(lossForm, {
    reportlossId: row.reportlossId,
    reportlossType: row.reportlossType,
    orderNumber: row.orderNumber,
    orderCreator: row.orderCreator,
    orderCreatorTime: row.orderCreatorTime,
    note: row.note,
    products: []
  })
  // 获取产品信息
  fetchProducts(row.reportlossId)
  dialogVisible.value = true
}
const lossesproducts = ref([])
// 获取产品数据(支持新增和编辑模式)
const fetchProducts = async (reportlossId?: string) => {
  if (reportlossId) {
    // 编辑模式：获取指定报损单的产品
    const res = await http.get(`/lssueread/api/Reportloss/GetReportlossProduct?ReportlossId=${reportlossId}`)
    if (res.data.code === 200) {
      lossesproducts.value = res.data.data
    }
  } else {
    // 新增模式：获取可选产品列表(这里需要替换为实际的产品选择接口)
    const res = await http.get('/lssueread/api/Reportloss/GetReportlossProduct?ReportlossId')
    if (res.data.code === 200) {
      lossesproducts.value = res.data.data
    }
  }
}


// // 提交表单
// const submitForm = () => {
//   // 根据编辑/新增模式调用不同接口
//   const apiUrl = isEdit.value ? '/api/Reportloss/UpdateReportloss' : '/api/Reportloss/CreateReportloss'
//   axios.post(apiUrl, {
//     reportlossId: lossForm.reportlossId,
//     reportlossType: lossForm.reportlossType,
//     orderNumber: lossForm.orderNumber,
//     orderCreator: lossForm.orderCreator,
//     orderCreatorTime: lossForm.orderCreatorTime,
//     note: lossForm.note,
//     products: lossForm.products.map(item => ({
//       productCode: item.productCode,
//       quantity: item.quantity,
//       batchNo: item.batchNo,
//       price: item.price,
//       locationName: item.locationName
//     }))
//   }).then(res => {
//     if (res.data.code === 200) {
//       ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
//       closeDialog()
//       ShowReportlosses() // 刷新列表
//     } else {
//       ElMessage.error(res.data.message)
//     }
//   })
// }
const closeDialog = () => {
  dialogVisible.value = false
}
</script>

<style scoped>
.losses-page {
  background: #f5f6fa;
  min-height: 100vh;
  padding: 20px;
}

.filter-card {
  margin-bottom: 18px;
}

.filter-title {
  font-weight: bold;
  font-size: 15px;
  margin-bottom: 8px;
}

.filter-form {
  margin-top: 8px;
  display: flex;
  align-items: center;
}

.table-card {
  padding-bottom: 0;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0;
}

.table-title {
  font-weight: bold;
  font-size: 15px;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.table-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.batch-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.el-table th,
.el-table td {
  text-align: center;
}
</style>
